function nextBeautifulNumber(n) {
  function isBalanced(x) {
    const count = new Array(10).fill(0);
    const s = x.toString();
    for (const c of s) {
      const d = parseInt(c, 10);
      count[d]++;
    }
    for (const c of s) {
      const d = parseInt(c, 10);
      if (count[d] !== d) {
        return false;
      }
    }
    return true;
  }

  let x = n + 1;
  while (true) {
    if (isBalanced(x)) {
      return x;
    }
    x++;
  }
}
